package com.asiainfo.indb.control.db;

import com.asiainfo.indb.control.db.pool.DbPoolFactory;
import com.asiainfo.indb.control.db.pool.IDbPool;
import com.asiainfo.indb.model.InDbGather;
import org.apache.commons.lang3.StringUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据库工具
 *
 * @author zym
 * @date 2019-10-18 15:43
 */
public class DbTool {

    /**
     * 获取表的所有列
     *
     * @param tableName 表名
     * @param dbData    连接数据
     * @return list
     * @throws SQLException exp
     */
    public static List<String> getTableCols(String tableName, InDbGather dbData) throws SQLException {
        if (StringUtils.isNotBlank(tableName) && dbData != null && dbData.size() > 0) {
            IDbPool pool = DbPoolFactory.getPool(dbData);
            if (pool != null) {
                try (Connection connection = pool.getConnection()) {
                    Statement statement = connection.createStatement();
                    ResultSet resultSet = statement.executeQuery(pool.getDialect().getColsSQL(tableName));

                    // 获取列信息
                    ResultSetMetaData metaData = resultSet.getMetaData();
                    int count = metaData.getColumnCount();
                    List<String> colList = new ArrayList<>(count);
                    for (int i = 1; i <= count; i++) {
                        colList.add(metaData.getColumnName(i));
                    }

                    return colList;
                }
            }
        }

        return null;
    }

}